import http from '@/axios/http'
import { json } from 'stream/consumers'

// 定义基础URL
const BASE_URL = 'http://192.140.166.207:8088/UserAppLogin/'

// const BASE_URL = "172.172.9.1:8080/user";

// 统一的请求处理函数
const handleRequest = async (url, params) => {
  try {
    const res = await http.post(url, params)
    if (res.code === 200) {
      return res.data
    }
    throw new Error(res.message || '请求失败')
  } catch (error) {
    console.error(`API请求错误: ${error.message}`, error)
    throw error
  }
}

const userLogin = {
  /**
   * 用户登录
   * @param data 登录参数 {username, password}
   * @returns Promise 包含用户数据的Promise
   */
  login: (params: any) => {
    return http
      .post('/TeachersController/login', params)
      .then((res) => {
        if (res.code == 200) {
          localStorage.setItem('token', JSON.stringify(res.data))
          return res // 登录成功，返回数据
        } else {
          // 登录失败，抛出错误以便外部catch捕获
          throw new Error(res.message || 'Login failed')
        }
      })
      .catch((error) => {
        // 统一处理错误
        console.error('Error during login:', error)
        throw error // 继续抛出错误，让调用方可以捕获
      })
  },

    // 获取用户信息
    // selectAll: (params: any) => {
    //     return http.post("/user/selectAll", params).then(res=>{
    //         if(res.code == 200){
    //             return res;
    //         }else{
    //             throw new Error(res.message || 'FIND failed');
    //         }
    //     }).catch(error=>{
    //         // 统一处理错误
    //         console.error('Error during FIND:', error);
    //         throw error; // 继续抛出错误，让调用方可以捕获
    //     });
    // },http://localhost:8088/api/UserAppLogin/findAll
    selectAll: (params: any) => {
        return http.post(BASE_URL+"findAll", params).then(res=>{
            if(res.code == 200){
                return res;
            }else{
                throw new Error(res.message || 'FIND failed');
            }
        }).catch(error=>{
            // 统一处理错误
            console.error('Error during FIND:', error);
            throw error; // 继续抛出错误，让调用方可以捕获
        });
    },
    
    findById: (params: any) => {
        return http.get(BASE_URL+"findById", params).then(res=>{
            if(res.code == 200){
                return res;
            }else{
                throw new Error(res.message || 'FIND failed');
            }
        }).catch(error=>{
            // 统一处理错误
            console.error('Error during FIND:', error);
            throw error; // 继续抛出错误，让调用方可以捕获
        });
    },
    //
    // update: (params: any) => handleRequest(`${BASE_URL}/update`, params),
    // insert: (params: any) => handleRequest(`${BASE_URL}/insert`, params),
    // deletUser: (params: any) => handleRequest(`${BASE_URL}/deletUser`, params),
    // 删除用户
    deletUser: (params: any) => {
        return http.delete(BASE_URL+"deletById", params).then(res=>{
            if(res.code == 200){
                return res.data;
            }else{
                // 登录失败，抛出错误以便外部catch捕获
                throw new Error(res.message || 'DELET failed');
            }
        }).catch(error=>{
            // 统一处理错误
            console.error('Error during DELET:', error);
            throw error;
        });
    },

    // 新增用户
    insert: (params: any) => {
        return http.post(BASE_URL+"register", params).then(res=>{
            if(res.code == 200){
                return res.data;
            }else{
                // 登录失败，抛出错误以便外部catch捕获
                throw new Error(res.message || 'DELET failed');
            }
        }).catch(error=>{
            // 统一处理错误
            console.error('Error during DELET:', error);
            throw error;
        });
    },

    //编辑用户
    update: (params: any) => {
        return http.post(BASE_URL+"updateById", params).then(res=>{
            if(res.code == 200){
                return res.data;
            }else{
                // 登录失败，抛出错误以便外部catch捕获
                throw new Error(res.message || 'DELET failed');
            }
        }).catch(error=>{
            // 统一处理错误
            console.error('Error during DELET:', error);
            throw error;
        });
    },
    // 用户登出
    logout: (data: any) => {
        return http.post("/user/logout", data);
    },
   //手机号码登录
    phoneLogin:(params: any) => {
        return http.post("/TeachersController/phoneLogin", params)
            .then(res => {
                if(res.code == 200){
                    return res; // 登录成功，返回数据
                }else{
                    // 登录失败，抛出错误以便外部catch捕获
                    throw new Error(res.message || 'Login failed');
                }
            })
            .catch(error => {
                // 统一处理错误
                console.error('Error during login:', error);
                throw error; // 继续抛出错误，让调用方可以捕获
            });
    },
    checkCode:(params: any) => {
        return http.post("/TeachersController/checkCode", params)
            .then(res => {
                if(res.code == 200){
                    localStorage.setItem("token",JSON.stringify(res.data))
                    return res; // 登录成功，返回数据
                }else{
                    // 登录失败，抛出错误以便外部catch捕获
                    throw new Error(res.message || 'Login failed');
                }
            })
            .catch(error => {
                // 统一处理错误
                console.error('Error during login:', error);
                throw error; // 继续抛出错误，让调用方可以捕获
            });
    },
};

export default userLogin
